﻿using M_Manufacture.Repository.Impl;
using M_Manufacture.Repository.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace M_Manufacture.Repository.Extensions
{
    public static class ServiceCollectionExtension
    {
        public static IServiceCollection AddService(this IServiceCollection services)
        {
            services.AddScoped<IWorkOrderRepository, WorkOrderRepository>();
            services.AddScoped<IProductionPlanRepository, ProductionPlanRepository>();

            return services;
        }

        public static IServiceCollection AddDb(this IServiceCollection services, string conn)
        {
            services.AddDbContext<EFDbContext>(x =>
            x.UseMySql(conn, ServerVersion.AutoDetect(conn)));

            return services;
        }

        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            //  添加JWT验证        认证使用             配置                服务
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
            {

                // 私钥             字节数组       编码           配置         JwtTokenOptions            安全密钥
                var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JwtTokenOptions:SecurityKey"]);
                // 验证参数         令牌验证参数      
                o.TokenValidationParameters = new TokenValidationParameters()
                {
                    // 验证发布者
                    ValidateIssuer = true,
                    // 发布者信息
                    ValidIssuer = builder.Configuration["JwtTokenOptions:Issuer"],

                    // 验证接收者
                    ValidateAudience = true,
                    // 接收者
                    ValidAudience = builder.Configuration["JwtTokenOptions:Audience"],

                    // 验证是否过期
                    ValidateLifetime = false,


                    // 验证私钥
                    IssuerSigningKey = new SymmetricSecurityKey(secretByte)

                };
            });
        }
    }
}
